package com.aft.terra.common.interceptor;

import java.util.HashMap;
import java.util.Map;

import com.aft.terra.app.Constants;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

public class PhoneInterceptor implements Interceptor {

	public void intercept(Invocation invocation) {
		Controller controller = invocation.getController();
		String phone = controller.getPara("phone");
		if (StrKit.isBlank(phone)) {
			controller.redirect("/");
			return;
		}

		String host = "http://ali-mobile.showapi.com/6-1";
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", "APPCODE 896ae34458174678a15bba69d5443913");
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("num", phone);
		String result = "";
		try {
			result = HttpKit.get(host, querys, headers);
		} catch (RuntimeException e) {
			e.printStackTrace();
			controller.redirect("/");
			return;
		}

		JSONObject js = JSONObject.parseObject(result);
		if (!Constants.PHONE_PROVINCE
				.equals(JSONObject.parseObject(String.valueOf(js.get("showapi_res_body"))).get("prov"))) {
			controller.setAttr("message", "感谢您的关注，仅支持吉林省内手机用户参与");
			controller.render("/member/addPhone.html");
			return;
		}
		invocation.invoke();
	}
}
